import { HttpException, Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { FavoriteEntity } from './entities/favorite.entity'
import { listFavoriteDto } from './dto/list-favorite.dto'
import { FavoriteItemDto } from './dto/favorite-item.dto'

@Injectable()
export class FavoriteService {
  constructor(
    @InjectRepository(FavoriteEntity)
    private readonly favoriteRepo: Repository<FavoriteEntity>,
  ) { }

  // 获取用户收藏列表
  async getFavoriteList(userId: number, data: listFavoriteDto) {
    const { page, pageSize } = data

    const qb = await this.favoriteRepo.createQueryBuilder('favorite')
    qb.leftJoinAndSelect('favorite.menu', 'menu')
    qb.orderBy('favorite.create_time', 'DESC')
    qb.andWhere('favorite.user_id = :user_id', { user_id: userId })

    if (!page && !pageSize) {
      const favorites = await qb.getMany()
      return {
        entries: this.formatFavorites(favorites),
        total: favorites.length
      }
    }
    const pageNum = Math.max(1, Number(page) || 1)
    const pageSizeNum = Math.min(100, Math.max(1, Number(pageSize) || 10))
    const [favorites, total] = await qb
      .skip((pageNum - 1) * pageSizeNum)
      .take(pageSizeNum)
      .getManyAndCount()

    return {
      entries: this.formatFavorites(favorites),
      total
    }
  }

  // 添加收藏
  async addFavorite(userId: number, menuId: number) {
    // 检查是否已收藏
    const exist = await this.favoriteRepo.exists({
      where: { user_id: userId, menu_id: menuId }
    })

    if (exist) throw new HttpException('该菜品已收藏', 409)

    await this.favoriteRepo.insert({
      user_id: userId,
      menu_id: menuId,
      create_time: Math.floor(Date.now() / 1000)
    })
    return {
      success: true,
      is_favorite: true
    }
  }

  // 取消收藏
  async removeFavorite(userId: number, menuId: number) {
    const exist = await this.favoriteRepo.exists({
      where: { user_id: userId, menu_id: menuId }
    })

    if (!exist) throw new HttpException('该菜品未收藏', 404)

    const result = await this.favoriteRepo.delete({
      user_id: userId,
      menu_id: menuId,
    })
    return {
      success: result.affected === 1,
      is_favorite: false,
    }
  }

  // 检查收藏状态
  async checkFavorite(userId: number, menuId: number): Promise<boolean> {
    const record = await this.favoriteRepo.exists({
      where: { user_id: userId, menu_id: menuId }
    })
    return record
  }

  // 获取用户所有收藏的菜品ID
  async getUserFavorites(userId: number): Promise<number[]> {
    const records = await this.favoriteRepo.find({
      where: { user_id: userId },
      select: ['menu_id'],
    })
    return records.map((r) => r.menu_id)
  }

  private formatFavorites(favorites: FavoriteEntity[]): FavoriteItemDto[] {
    return favorites.map(item => ({
      id: item.id,
      menu_id: item.menu_id,
      menu_info: {
        name: item.menu.name,
        fee: item.menu.fee,
        photo_url: item.menu.photo_url
      }
    }))
  }
}